package com.eternallove.config.quartz;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.eternallove.biz.system.SystemJobSnippetTriggerBiz;
import com.eternallove.biz.system.dto.TriggerJobSnippetDTO;
import com.eternallove.core.constants.Constants;
import com.eternallove.dao.system.SystemJobSnippetMapper;
import com.eternallove.dao.system.model.SystemJobSnippet;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 分片任务扫描器
 * 该处理器每1秒扫描SYSTEM_JOB_SNIPPET表，执行还未执行的分片任务
 * @author Eva.Caesar Liu
 * @since 2022/11/30 15:45
 */
@Slf4j
@Component
@DisallowConcurrentExecution
public class SnippetScanner extends QuartzJobBean {

    @Autowired
    private SystemJobSnippetTriggerBiz systemJobSnippetTriggerBiz;

    @Autowired
    private SystemJobSnippetMapper systemJobSnippetMapper;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {
            log.trace("Snippet scanner started.");
            // 1. 查询所有未执行的分片任务
            List<SystemJobSnippet> snippets = systemJobSnippetMapper.selectList(new LambdaQueryWrapper<SystemJobSnippet>()
                    .select(SystemJobSnippet::getId)
                    .eq(SystemJobSnippet::getStatus, Constants.Job.JobStatus.READY.getCode())
                    .orderByAsc(SystemJobSnippet::getCreateTime)
            );
            // 2. 循环执行
            for (SystemJobSnippet snippet : snippets) {
                TriggerJobSnippetDTO dto = new TriggerJobSnippetDTO();
                dto.setId(snippet.getId());
                dto.setTriggerType(Constants.Job.TriggerType.SYSTEM.getCode());
                systemJobSnippetTriggerBiz.trigger(dto);
            }
        } catch (Exception e) {
            throw new JobExecutionException("EVA: trigger snippet throw an exception", e);
        } finally {
            log.trace("Snippet scanner execute completed.");
        }
    }
}
